package com.zjmzxfzhl.modules.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zjmzxfzhl.common.core.constant.SysConstants;
import com.zjmzxfzhl.common.core.exception.SysException;
import com.zjmzxfzhl.common.core.util.CommonUtil;
import com.zjmzxfzhl.common.core.util.SecurityUtils;
import com.zjmzxfzhl.modules.app.entity.*;
import com.zjmzxfzhl.modules.app.form.*;
import com.zjmzxfzhl.modules.app.service.*;
import com.zjmzxfzhl.modules.sys.entity.SysUser;
import com.zjmzxfzhl.modules.sys.entity.vo.ElTree;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zjmzxfzhl.common.core.base.BaseServiceImpl;
import com.zjmzxfzhl.modules.app.mapper.AppTaskMapper;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Service
 * 
 * @author 张森荣
 */
@Service
public class AppTaskServiceImpl extends BaseServiceImpl<AppTaskMapper, AppTask>
        implements AppTaskService {
    @Autowired
    private AppTaskUserService appTaskUserService;
    @Autowired
    private AppTaskTagService appTaskTagService;
    @Autowired
    private AppLogService appLogService;
    @Autowired
    private AppMptService appMptService;
    @Autowired
    private AppProjUserService appProjUserService;
    @Autowired
    private AppModiService appModiService;
    @Autowired
    private AppProjService appProjService;
    @Autowired
    private AppDocService appDocService;

    @Override
    public IPage<AppTask> list(IPage<AppTask> page, AppTaskVo appTask) {
        return page.setRecords(baseMapper.list(page, appTask));
    }

    /**
     * 统计任务数量
     * @return
     */
    @Override
    public List<TaskTotalVo> taskTotal(AppTask appTask) {
        return baseMapper.taskTotal(appTask);
    }
    @Override
    public TaskSumVo getTaskSun(String masterUserId,String projId) {
        return baseMapper.getTaskSun(masterUserId,projId);
    }
    @Override
    public Integer selectRowCount(AppTaskVo appTaskVo) {
        return baseMapper.selectRowCount(appTaskVo);
    }
    @Override
    public Integer timeoutCount(String mptId) {
        return baseMapper.timeoutCount(mptId);
    }
    @Override
    public Integer notFinishCount(String mptId) {
        return baseMapper.notFinishCount(mptId);
    }

    /**
     * 移动机构树，自动计算机构级别、机构级次码、是否叶子
     *
     * @param appTask
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean moveTree(AppTask appTask,String parentId) {
        Boolean result = true;

        if (CommonUtil.isEmptyStr(appTask.getParentTaskId())) {
            appTask.setTaskLevel("1");
            appTask.setTaskLevelCode(appTask.getOrgId());
            result = this.updateById(appTask);
        } else {
            // 父节点
            AppTask parentAppTask = this.getById(appTask.getParentTaskId());
            if (parentAppTask == null) {
                throw new SysException("保存失败,上级机构ID【" + parentAppTask.getParentTaskId() + "】不存在!");
            }
            // 【2】计算机构级次,机构级次码
            // 【2-a】设置新增机构的父机构是否叶子为否
            if (!SysConstants.IS_LEAF_0.equals(parentAppTask.getIsLeaf())) {
                parentAppTask.setIsLeaf(SysConstants.IS_LEAF_0);
                this.updateById(parentAppTask);
            }
            Integer taskLevel = Integer.valueOf(parentAppTask.getTaskLevel()) + 1;
            appTask.setTaskLevel(taskLevel.toString());
            appTask.setTaskLevelCode(parentAppTask.getTaskLevelCode() + "," + appTask.getOrgId());
            result = this.updateById(appTask);
        }
        if (result == true) {
            //不为叶子节点时更改子树的层级，路径
            if (SysConstants.IS_LEAF_0.equals(appTask.getIsLeaf())) {
                AppTaskVo selectTask = new AppTaskVo();
                selectTask.setTaskLevelCode(appTask.getTaskId());

                List<AppTask> appTaskList = baseMapper.list(null, selectTask);
                if (appTaskList.size() > 0) {
                    for (AppTask task : appTaskList) {
                        if (task.getTaskLevelCode().indexOf(appTask.getTaskId()) != -1) {
                            //替换树路径
                            int sub = task.getTaskLevelCode().indexOf(appTask.getTaskId()) + appTask.getTaskId().length();
                            task.setTaskLevelCode(appTask.getTaskLevelCode() + task.getTaskLevelCode().substring(sub));
                            //根据树路径修改层级
                            String[] codeArr = task.getTaskLevelCode().split(",");
                            Integer level = codeArr.length;
                            task.setTaskLevel(level.toString());
                            this.updateById(task);
                        }
                    }
                }
            }
        }
        //判断原父节点是否成为新为叶子
        if (parentId != null && !"".equals(parentId)) {
            inspectParent(parentId);
        }
        return result;
    }

    /**
     * 新增机构，自动计算机构级别、机构级次码、是否叶子
     *
     * @param appTask
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveAppTask(AppTask appTask) {
        //保存项目成员数组，标签数组
        List<SysUser> userList=null;
        List<AppTag> tags=null;
        if(appTask.getUserList()!=null){
            userList=appTask.getUserList();
        }
        if(appTask.getTags()!=null){
            tags=appTask.getTags();
        }

        //判断是否存在不属于父项目成员
        if (appTask.getProjId() != null&&!"".equals(appTask.getProjId())) {
            if (!appProjUserService.checkMembers(userList, appTask.getProjId())) {
                throw new SysException("存在不属于项目的参与成员！");
            }
            //判断负责人是否为父项目成员
            if (appTask.getMasterUserId() != null && !"".equals(appTask.getMasterUserId())) {
                List<String> projUserIdList = appProjUserService.selectUserIdList(appTask.getProjId());
                if (!projUserIdList.contains(appTask.getMasterUserId())) {
                    throw new SysException("负责人不属于项目的参与成员！");
                }
            }
        }

        //添加项目
        appTask =setAppTask(appTask);
        Boolean result = this.save(appTask);
        if(result==false){
            return result;
        }
        appTask=this.getById(appTask.getTaskId());
        // 【1】 校验id是否重复.
        if (CommonUtil.isEmptyStr(appTask.getParentTaskId())) {
            appTask.setTaskLevel("1");
            appTask.setTaskLevelCode(appTask.getTaskId());
            appTask.setIsLeaf(SysConstants.USER_STATUS_1);
            result = this.updateById(appTask);
        } else {

            // 父节点
            AppTask parentAppTask = this.getById(appTask.getParentTaskId());
            if (parentAppTask == null) {
                throw new SysException("保存失败,上级机构ID【" + appTask.getParentTaskId() + "】不存在!");
            }
            // 【2】计算机构级次,机构级次码
            // 【2-a】设置新增机构的父机构是否叶子为否
            if (!SysConstants.IS_LEAF_0.equals(parentAppTask.getIsLeaf())) {
                parentAppTask.setIsLeaf(SysConstants.IS_LEAF_0);
                this.updateById(parentAppTask);
            }
            Integer TaskLevel = Integer.valueOf(parentAppTask.getTaskLevel()) + 1;
            appTask.setTaskLevel(TaskLevel.toString());
            appTask.setTaskLevelCode(parentAppTask.getTaskLevelCode() + "," + appTask.getTaskId());

            // 【3】设置新增机构是否叶子为 是；
            appTask.setIsLeaf("1");
            result = this.updateById(appTask);
        }

        AppLog appLog=new AppLog();
        appLog.setContent("创建新任务标题为"+appTask.getName());
        appLog.setLogType("01");
        appLog.setLogTypeId(appTask.getTaskId());
        appLogService.save(appLog);

        //添加项目成员，项目标签
        if(userList!=null){
            for (SysUser user:userList) {
                AppTaskUser appTaskUser=new AppTaskUser();
                appTaskUser.setTaskId(appTask.getTaskId());
                appTaskUser.setUserId(user.getUserId());
                appTaskUserService.saveAppTaskUser(appTaskUser);
            }
        }
        if(tags!=null){
            for (AppTag tag:tags) {
                AppTaskTag appTaskTag=new AppTaskTag();
                appTaskTag.setTaskId(appTask.getTaskId());
                appTaskTag.setTagId(tag.getTagId());
                appTaskTagService.saveAppTaskTag(appTaskTag);
            }
        }

        //判断里程碑是否开始、逾期
        appMptService.inProgress(appTask.getMptId());
        appMptService.timeout(appTask.getMptId());
        return result;
    }

    private AppTask setAppTask(AppTask appTask){
        if (appTask.getStatus() == null || "".equals(appTask.getStatus())) {
            appTask.setStatus("00");
        }
        if (appTask.getTaskLevel() == null || "".equals(appTask.getTaskLevel())) {
            appTask.setTaskLevel("0");
        }
        if (appTask.getTaskLevelCode() == null) {
            appTask.setTaskLevelCode("");
        }
        if (appTask.getTaskType() == null || "".equals(appTask.getTaskType())) {
            appTask.setTaskType("06");
        }
        if(appTask.getMasterUserId()==null|| "".equals(appTask.getMasterUserId())){
            appTask.setMasterUserId(SecurityUtils.getUserId());
        }
        if (appTask.getMatrix() == null || "".equals(appTask.getMatrix())) {
            appTask.setMatrix("02");
        }
        //计算预计工时
        if(appTask.getStartDate()!=null&&appTask.getEndDate()!=null){
            if(appTask.getEndDate().getTime()>=appTask.getStartDate().getTime()){
                appTask.setTaskTime(workingHours(appTask.getStartDate(),appTask.getEndDate()));
            }
        }
        return appTask;
    }

    //计算工时
    private Integer workingHours(Date startDate,Date endDate){
        int weekend=0;
        Calendar cal = Calendar.getInstance();
        cal.setTime(startDate);
        Integer start = cal.get(Calendar.DAY_OF_WEEK)-1;
        cal.setTime(endDate);
        Integer end = cal.get(Calendar.DAY_OF_WEEK)-1;
        Integer days=(int) ((endDate.getTime() - startDate.getTime()) / (1000*3600*24))+1;
        if(days==1){
            if (start == 0 || start == 6) {
                weekend = weekend + 1;
            }
        }else {
            weekend =weekend + (days/7)*2;
            if(days%7!=0){
                if (start==0&&end==6) {
                    weekend += 2;
                }else if (start<end&&end==6){
                    weekend+=1;
                }else if (start<end&&start==0){
                    weekend+=1;
                }else if (start>end){
                    weekend+=2;
                }
                if (start==end){
                    if (start==6||end==0){
                        weekend+=1;
                    }
                }
            }
        }
        return days-weekend;
    }
    /**
     * 机构管理，机构树数据
     *
     * @return
     */
    @Override
    public List<ElTree> getTreeData(AppTaskVo appTaskVo,Integer current,Integer size,String parentId,Integer level) {
        List<AppTask> taskList=null;
        if (parentId == null && level == null) {
            //查找一级节点
            appTaskVo.setTaskLevel("1");
            taskList = baseMapper.list(new Page<AppTask>(current, size), appTaskVo);
        }else
        {//按层级展开节点
            Integer parentLevel=null;
            if (parentId != null&&!"".equals(parentId)) {
                AppTask parentTask = this.getById(parentId);
                parentLevel=Integer.valueOf(parentTask.getTaskLevel());
            }
            taskList =  baseMapper.treeData(parentId,level,parentLevel);
        }
        if (taskList != null) {
            if (appTaskVo.getIsDoc() != null && appTaskVo.getIsDoc() == 1) {
                for (AppTask task:taskList) {
                    AppDocVo appDocVo=new AppDocVo();
                    appDocVo.setDocType("01");
                    appDocVo.setDocTypeId(task.getTaskId());
                    List<AppDocVo> appDocVos=appDocService.getList(null,appDocVo);
                    if(appDocVos.size()>0){
                        task.setDocList(appDocVos);
                    }
                }
            }
            return makeOrgTree(taskList);
        }

        return null;
    }

    /**
     * 生成机构树
     *
     * @param taskList
     * @return
     */
    public List<ElTree> makeOrgTree(List<AppTask> taskList) {
        Map<String, ElTree> orgMap = new LinkedHashMap<String, ElTree>();
        for (AppTask appTask : taskList) {
            ElTree elTree = new ElTree();
            elTree.setId(appTask.getTaskId());
            elTree.setLabel(appTask.getName());
            elTree.setIsLeaf("1".equals(appTask.getIsLeaf()));
            elTree.setData(appTask);
            orgMap.put(appTask.getTaskId(), elTree);
            if (CommonUtil.isNotEmptyStr(appTask.getParentTaskId()) && orgMap.containsKey(appTask.getParentTaskId())) {
                elTree.setParentId(appTask.getParentTaskId());
                ElTree parentElTree = orgMap.get(appTask.getParentTaskId());
                parentElTree.addChildren(elTree);
            }
        }

        List<ElTree> result = new ArrayList<ElTree>();
        orgMap.forEach((k, v) -> {
            if (CommonUtil.isEmptyStr(v.getParentId())) {
                result.add(v);
            }
        });
        List<ElTree> sortElTree=sort(result);
        return sortElTree;
    }

    /**
     * 排序
     *
     * @param items
     *            排序
     * @return 排序
     */
    private List<ElTree> sort(List<ElTree> items) {
        List<ElTree> result = new ArrayList<ElTree>();
        if (items != null) {
            Collections.sort(items, new Comparator<ElTree>() {
                public int compare(ElTree n1, ElTree n2) {
                    AppTask org1=(AppTask)n1.getData();
                    AppTask org2=(AppTask)n2.getData();
                    if (org1.getCreateTime()==null) {
                        return -1;
                    }
                    if (org2.getCreateTime()==null) {
                        return 1;
                    }
                    return org1.getCreateTime().compareTo(org2.getCreateTime());
                }
            });
            for (ElTree item : items) {
                result.add(item);
                item.setChildren(sort(item.getChildren()));
            }
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delByIds(String ids) {
        Boolean result = true;
        String[] idsArr = ids.split(",");

        result = isRemove(idsArr);
        if (result == false) {
            return result;
        }
        for (String s:idsArr) {
            AppTask appTask=baseMapper.selectById(s);
            result= this.removeById(s);
            if(appTask.getParentTaskId()!=null && !"".equals(appTask.getParentTaskId())){
            inspectParent(appTask.getParentTaskId());
            }
        }
        return result;
    }

    private boolean isRemove(String[] idsArr){
        Boolean result = true;
        for (String s:idsArr) {
            AppTask appTask = baseMapper.selectById(s);
            //项目不存在
            if (appTask == null) {
                result = false;
            }
            //不为叶子节点
            if ("0".equals(appTask.getIsLeaf())) {
                result = false;
            }
        }
        return result;
    }

    //检查父节点是否为子树
    private void inspectParent(String parentId){
        Integer total = this.count(new LambdaQueryWrapper<AppTask>().eq(AppTask::getParentTaskId, parentId));
        if (total <= 0) {
            AppTask parentAppTask=this.getById(parentId);
            parentAppTask.setIsLeaf(SysConstants.USER_STATUS_1);
            this.updateById(parentAppTask);
        }
    }
    /**
     * 变更任务状态（待办的）
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean wait(String taskId) {
       AppTask appTask=this.getById(taskId);
       if(appTask==null){
           return false;
       }
       appTask.setStatus("00");
        appTask.setWorkStartDate(null);
        appTask.setWorkEndDate(null);
        appTask.setUpdateTime(new Date());
        Boolean result = this.updateById(appTask);

        appLogService.addLog("变更任务状态为 待办的","01",appTask.getTaskId());
        //判断里程碑是否逾期
        appMptService.timeout(appTask.getMptId());
        return result;
    }
    /**
     * 已确认
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean confirmed(String taskId) {
        AppTask appTask=this.getById(taskId);
        if(appTask==null){
            return false;
        }
//        if(!"00".equals(appTask.getStatus())){
//            throw new SysException("任务不处于待办状态无法确认");
//        }
        appTask.setStatus("01");
        appTask.setWorkStartDate(null);
        appTask.setWorkEndDate(null);
        appTask.setUpdateTime(new Date());
        Boolean result = this.updateById(appTask);

        appLogService.addLog("变更任务状态为 已确认","01",appTask.getTaskId());
        //判断里程碑是否开始、逾期
        appMptService.inProgress(appTask.getMptId());
        appMptService.timeout(appTask.getMptId());
        return result;
    }
    /**
     * 设计中
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean inDesign(String taskId) {
        AppTask appTask=this.getById(taskId);
        if(appTask==null){
            return false;
        }
        if("00".equals(appTask.getStatus())){
            throw new SysException("任务未确认无法开始");
        }
        appTask.setWorkStartDate(new Date());
        appTask.setStatus("02");
        appTask.setUpdateTime(new Date());
        Boolean result = this.updateById(appTask);

        appLogService.addLog("变更任务状态为 设计中","01",appTask.getTaskId());
        //判断里程碑是否逾期
        appMptService.timeout(appTask.getMptId());
        return result;
    }
    /**
     * 开发中
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean inDevelop(String taskId) {
        AppTask appTask=this.getById(taskId);
        if(appTask==null){
            return false;
        }
        if("00".equals(appTask.getStatus())){
            throw new SysException("任务未确认无法开始");
        }
        appTask.setWorkStartDate(new Date());
        appTask.setStatus("04");
        appTask.setUpdateTime(new Date());
        Boolean result = this.updateById(appTask);

        appLogService.addLog("变更任务状态为 开发中","01",appTask.getTaskId());
        //判断里程碑是否逾期
        appMptService.timeout(appTask.getMptId());
        return result;
    }
    /**
     * 修复中
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean inRepair(String taskId) {
        AppTask appTask=this.getById(taskId);
        if(appTask==null){
            return false;
        }
        if("00".equals(appTask.getStatus())){
            throw new SysException("任务未确认无法开始");
        }
        appTask.setWorkStartDate(new Date());
        appTask.setStatus("05");
        appTask.setUpdateTime(new Date());
        Boolean result = this.updateById(appTask);

        appLogService.addLog("变更任务状态为 修复中","01",appTask.getTaskId());
        //判断里程碑是否逾期
        appMptService.timeout(appTask.getMptId());
        return result;
    }
    /**
     * 进行中
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean inProgress(String taskId) {
        AppTask appTask=this.getById(taskId);
        if(appTask==null){
            return false;
        }
        if("00".equals(appTask.getStatus())){
            throw new SysException("任务未确认无法开始");
        }
        appTask.setWorkStartDate(new Date());
        appTask.setStatus("06");
        appTask.setUpdateTime(new Date());
        Boolean result = this.updateById(appTask);

        appLogService.addLog("变更任务状态为 进行中","01",appTask.getTaskId());
        //判断里程碑是否逾期
        appMptService.timeout(appTask.getMptId());
        return result;
    }
    /**
     * 已完成
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean finish(String taskId) {
        AppTask appTask=this.getById(taskId);
        if(appTask==null){
            return false;
        }
        if ("01".equals(appTask.getStatus()) || "00".equals(appTask.getStatus())||"09".equals(appTask.getStatus())) {
            throw new SysException("任务未开始无法完成");
        }
        appTask.setStatus("07");
        appTask.setWorkEndDate(new Date());
        if(appTask.getWorkStartDate()!=null&&appTask.getWorkEndDate()!=null){
            appTask.setTaskWorkTime(workingHours(appTask.getWorkStartDate(),appTask.getWorkEndDate()));
        }
        appTask.setUpdateTime(new Date());
        Boolean result = this.updateById(appTask);

        appLogService.addLog("变更任务状态为 已完成","01",appTask.getTaskId());
        //判断里程碑是否逾期
        appMptService.timeout(appTask.getMptId());
        return result;
    }
    /**
     * 已验收
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean verified(String taskId) {
        AppTask appTask=this.getById(taskId);
        if(appTask==null){
            return false;
        }
        String userId = SecurityUtils.getUserId();
        if(!"admin".equals(userId)) {
            if (!userId.equals(appTask.getCreateBy())) {
                throw new SysException("不是任务创建人，无法验收");
            }
        }
        if (!"07".equals(appTask.getStatus())) {
            throw new SysException("任务未完成无法验收");
        }
        appTask.setStatus("08");
        appTask.setUpdateTime(new Date());
        Boolean result = this.updateById(appTask);

        appLogService.addLog("变更任务状态为 已验收","01",appTask.getTaskId());
        //判断里程碑是否完成、逾期
        appMptService.finish(appTask.getMptId());
        appMptService.timeout(appTask.getMptId());
        return result;
    }
    /**
     * 已取消
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cancel(String taskId) {
        AppTask appTask=this.getById(taskId);
        if(appTask==null){
            return false;
        }
        if(!"00".equals(appTask.getStatus())&&!"01".equals(appTask.getStatus())){
            throw new SysException("任务已开始无法取消");
        }
        appTask.setStatus("09");
        appTask.setWorkStartDate(null);
        appTask.setWorkEndDate(null);
        appTask.setUpdateTime(new Date());
        Boolean result = this.updateById(appTask);

        appLogService.addLog("变更任务状态为 已取消","01",appTask.getTaskId());
        //判断里程碑是否逾期
        appMptService.timeout(appTask.getMptId());
        return result;
    }
    /**
     * 已拒绝
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean refused(String taskId) {
        AppTask appTask=this.getById(taskId);
        if(appTask==null){
            return false;
        }
        if(!"00".equals(appTask.getStatus())){
            throw new SysException("任务不处于待办状态无法拒绝");
        }
        appTask.setStatus("10");
        appTask.setUpdateTime(new Date());
        Boolean result = this.updateById(appTask);

        appLogService.addLog("变更任务状态为 已拒绝","01",appTask.getTaskId());
        return result;
    }

    /**
     * 已中止
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean suspend(String taskId) {
        AppTask appTask=this.getById(taskId);
        if(appTask==null){
            return false;
        }

        appTask.setStatus("11");
        appTask.setUpdateTime(new Date());
        Boolean result = this.updateById(appTask);

        appLogService.addLog("变更任务状态为 已中止","01",appTask.getTaskId());
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AppTask queryById(String id) {
        AppTaskVo appTaskVo=new AppTaskVo();
        appTaskVo.setTaskId(id);
        List<AppTask> appTaskList= baseMapper.list(null, appTaskVo);
        if(appTaskList.size()>0){
            return appTaskList.get(0);
        }
        return null;
    }


    /**
     * 新增机构，自动计算机构级别、机构级次码、是否叶子
     *
     * @param appTask
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateAppTask(AppTask appTask) {
        //保存修改项目成员数组，标签数组
        List<SysUser> userList=null;
        List<AppTag> tags=null;
        if(appTask.getUserList()!=null){
            userList=appTask.getUserList();
        }
        if(appTask.getTags()!=null){
            tags=appTask.getTags();
        }
        //修改任务
        AppTask task=this.queryById(appTask.getTaskId());
        if("08".equals(task.getStatus())){
            throw new SysException("任务已验收无法修改！");
        }
        if(!task.getName().equals(appTask.getName())){
            appLogService.addLog("变更任务 "+task.getName()+" 更改标题为 "+appTask.getName(),"01",appTask.getTaskId());
        }
        //计算预计工时
        if(appTask.getStartDate()!=null&&appTask.getEndDate()!=null){
            if(appTask.getEndDate().getTime()>=appTask.getStartDate().getTime()){
                appTask.setTaskTime(workingHours(appTask.getStartDate(),appTask.getEndDate()));
            }
        }
        appTask.setUpdateTime(new Date());
        Boolean result = this.updateById(appTask);
        if(result==false){
            return false;
        }
        //判断是否存在不属于父项目成员
        if (task.getProjId() != null && !"".equals(task.getProjId())) {
            if (!appProjUserService.checkMembers(userList, task.getProjId())) {
                throw new SysException("存在不属于项目的参与成员！");
            }
            //判断负责人是否为父项目成员
            if (appTask.getMasterUserId() != null && !"".equals(appTask.getMasterUserId())) {
                List<String> projUserIdList = appProjUserService.selectUserIdList(task.getProjId());
                if (!projUserIdList.contains(appTask.getMasterUserId())) {
                    throw new SysException("负责人不属于项目的参与成员！");
                }
            }
        }

        //添加任务操作记录
        appLogService.addLog("变更任务内容","01",appTask.getTaskId());

        //删除原项目成员，项目标签
        //添加修改项目成员，项目标签
        if(userList!=null){
            AppTaskUser appTaskUser=new AppTaskUser();
            appTaskUser.setTaskId(appTask.getTaskId());
            appTaskUserService.relationDel(appTaskUser);
            for (SysUser user:userList) {
                appTaskUser.setUserId(user.getUserId());
                appTaskUserService.saveAppTaskUser(appTaskUser);
            }
        }
        if(tags!=null){
            AppTaskTag appTaskTag=new AppTaskTag();
            appTaskTag.setTaskId(appTask.getTaskId());
            appTaskTagService.relationDel(appTaskTag);
            for (AppTag tag:tags) {
                appTaskTag.setTagId(tag.getTagId());
                appTaskTagService.saveAppTaskTag(appTaskTag);
            }
        }
        return result;
    }

    /**
     * 项目任务甘特图数据
     *
     * @return
     */
    public  List<TaskGanttVo> ganttChart(AppTaskVo appTaskVo) {
        Map<String, TaskGanttVo> orgMap = new LinkedHashMap<String, TaskGanttVo>();
        List<TaskGanttVo> taskGanttVoList=baseMapper.taskGanttData(appTaskVo);
        for (TaskGanttVo taskGanttVo : taskGanttVoList) {
            //添加初始变更时间
            AppModiVo appModi=new AppModiVo();
            appModi.setModiType("01");
            appModi.setModiSubtype("10");
            appModi.setModiTypeId(taskGanttVo.getTaskId());
            appModi.setStatus("02");
            List<AppModiVo> appModiList=appModiService.getList(appModi);
            if(appModiList.size()>0){
                Date star=appModiList.get(0).getOldStartDate();
                Date end=appModiList.get(0).getOldEndDate();
                taskGanttVo.setInitialStartDate(taskGanttVo.getStartDate());//任务当前时间
                taskGanttVo.setInitialEndDate(taskGanttVo.getEndDate());//任务当前时间
                taskGanttVo.setStartDate(star);//任务初始时间
                taskGanttVo.setEndDate(end);//任务初始时间
            }

            taskGanttVo.setNowDate(new Date());
            orgMap.put(taskGanttVo.getTaskId(), taskGanttVo);
            taskGanttVo.setChildren(new ArrayList<>());
            if (CommonUtil.isNotEmptyStr(taskGanttVo.getParentTaskId()) && orgMap.containsKey(taskGanttVo.getParentTaskId())) {
                TaskGanttVo parentGanttVo = orgMap.get(taskGanttVo.getParentTaskId());
                parentGanttVo.addChildren(taskGanttVo);
            }
        }

        List<TaskGanttVo> result = new ArrayList<TaskGanttVo>();
        orgMap.forEach((k, v) -> {
            if (CommonUtil.isEmptyStr(v.getParentTaskId())) {
                result.add(v);
            }
        });
        List<TaskGanttVo> sortElTree=sortGanttChart(result);
        return sortElTree;
    }
    /**
     * 排序
     *
     * @param items
     *            排序
     * @return 排序
     */
    private List<TaskGanttVo> sortGanttChart(List<TaskGanttVo> items) {
        List<TaskGanttVo> result = new ArrayList<TaskGanttVo>();
        if (items != null) {
            Collections.sort(items, new Comparator<TaskGanttVo>() {
                public int compare(TaskGanttVo n1, TaskGanttVo n2) {
                    if (n1.getCreateTime()==null) {
                        return -1;
                    }
                    if (n2.getCreateTime()==null) {
                        return 1;
                    }
                    return n1.getCreateTime().compareTo(n2.getCreateTime());
                }
            });
            for (TaskGanttVo item : items) {
                result.add(item);
                item.setChildren(sortGanttChart(item.getChildren()));
            }
        }
        return result;
    }
    /**
     * 项目任务甘特图数据
     *
     * @return
     */
    public  List<MeetTaskVo> getMeetTask(String projId) {
        Map<String, MeetTaskVo> orgMap = new LinkedHashMap<String, MeetTaskVo>();
        List<MeetTaskVo> meetTaskVoList=baseMapper.getMeetTask(projId);
        for (MeetTaskVo meetTaskVo : meetTaskVoList) {
            orgMap.put(meetTaskVo.getTaskId(), meetTaskVo);
            if (CommonUtil.isNotEmptyStr(meetTaskVo.getParentTaskId()) && orgMap.containsKey(meetTaskVo.getParentTaskId())) {
                MeetTaskVo parentMeetTaskVo = orgMap.get(meetTaskVo.getParentTaskId());
                parentMeetTaskVo.addChildren(meetTaskVo);
            }
        }

        List<MeetTaskVo> result = new ArrayList<MeetTaskVo>();
        orgMap.forEach((k, v) -> {
            if (CommonUtil.isEmptyStr(v.getParentTaskId())) {
                result.add(v);
            }
        });

        List<MeetTaskVo> sortElTree=sortMeetTask(result);
        return sortElTree;
    }

    /**
     * 排序
     *
     * @param items
     *            排序
     * @return 排序
     */
    private List<MeetTaskVo> sortMeetTask(List<MeetTaskVo> items) {
        List<MeetTaskVo> result = new ArrayList<MeetTaskVo>();
        if (items != null) {
            Collections.sort(items, new Comparator<MeetTaskVo>() {
                public int compare(MeetTaskVo n1, MeetTaskVo n2) {
                    if (n1.getCreateTime()==null) {
                        return -1;
                    }
                    if (n2.getCreateTime()==null) {
                        return 1;
                    }
                    return n1.getCreateTime().compareTo(n2.getCreateTime());
                }
            });
            for (MeetTaskVo item : items) {
                result.add(item);
                item.setChildren(sortMeetTask(item.getChildren()));
            }
        }
        return result;
    }

    public  List<AppTask> getTaskList(String[] idsArr) {
        return baseMapper.getTaskList(idsArr);
    }
    /**
     * 变更任务（时间）
     *
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public AppTask modiTask(AppTask appTask) {
        AppTask task=this.queryById(appTask.getTaskId());
        if(task==null){
            throw new SysException("找不到变更任务！");
        }
        Date oldStartDate=task.getStartDate();
        Date oldEndDate=task.getEndDate();
        Date workStartDate=task.getWorkStartDate();
        Date workEndDate=task.getWorkEndDate();
        Integer oldWorkTime=task.getTaskWorkTime();

        task.setStartDate(appTask.getStartDate());
        task.setEndDate(appTask.getEndDate());
        task.setWorkStartDate(appTask.getWorkStartDate());
        task.setWorkEndDate(appTask.getWorkEndDate());
        task.setTaskWorkTime(appTask.getTaskWorkTime());
        //计算预计工时
        if(task.getStartDate()!=null&&task.getEndDate()!=null){
            if(task.getEndDate().getTime()>=task.getStartDate().getTime()){
                task.setTaskTime(workingHours(task.getStartDate(),task.getEndDate()));
            }
        }
        task.setUpdateTime(new Date());
        this.updateById(task);
        task=this.queryById(task.getTaskId());
        //添加变更记录
        AppModi appModi=new AppModi();
        appModi.setModiType("01");
        appModi.setModiSubtype("10");
        appModi.setModiTypeId(task.getTaskId());
        appModi.setContent("任务变更时间");
        appModi.setStatus("02");
        appModi.setOldStartDate(oldStartDate);
        appModi.setOldEndDate(oldEndDate);
        appModi.setWorkStartDate(workStartDate);
        appModi.setWorkEndDate(workEndDate);
        appModi.setOldWorkTime(oldWorkTime);
        appModiService.saveAppModi(appModi);

        return task;
    }

    /**
     * 变更任务（时间）
     *
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public List<AppTask> modiTaskList(String taskId) {
        AppTask task=this.queryById(taskId);
        if(task==null){
            throw new SysException("找不到变更任务！");
        }
        List<AppTask> appTaskList=new ArrayList<>();

        AppModiVo appModi=new AppModiVo();
        appModi.setModiType("01");
        appModi.setModiSubtype("10");
        appModi.setModiTypeId(task.getTaskId());
        appModi.setStatus("02");
        List<AppModiVo> appModiList=appModiService.getList(appModi);
        for (AppModiVo modi:appModiList) {
            AppTask modiTask=new AppTask();
            BeanUtils.copyProperties(task,modiTask);
            modiTask.setStartDate(modi.getOldStartDate());
            modiTask.setEndDate(modi.getOldEndDate());
            modiTask.setWorkStartDate(modi.getWorkStartDate());
            modiTask.setWorkEndDate(modi.getWorkEndDate());
            appTaskList.add(modiTask);
        }

        return appTaskList;
    }

    /**
     * 面包屑导航
     *
     * @return
     */
    public List<TaskCrumbVo> taskCrumb(String taskId) {
        List<TaskCrumbVo> result=new ArrayList<>();
        List<TaskCrumbVo> taskCrumbVoList=baseMapper.taskCrumb(taskId);
        if(taskCrumbVoList.size()>0){
            if(taskCrumbVoList.get(0).getParentTaskId()!=null){
                result.addAll(taskCrumb(taskCrumbVoList.get(0).getParentTaskId()));
            }
            result.add(taskCrumbVoList.get(0));
        }
//        Collections.reverse(result);
        return result;
    }

    /**
     * 获取项目任务周期
     *
     * @return
     */
    public List<TaskCycleVo> taskCycle(String projId) {
        List<TaskCycleVo> taskCycleVoList=baseMapper.taskCycle(projId);
        return taskCycleVoList;
    }
}
